<head>
    <title>神奇弹幕</title>
    <script src="../js/jquery.js"></script>
    <link rel="stylesheet" href="end_thanks.css" media="screen" type="text/css" />
    <link rel="stylesheet" href="end_thanks_custom.css" media="screen" type="text/css" />
</head>

<body>
    <div id="movie">
        <marquee id="list" direction="up" height="100%">
            <p>上船</p>
            <p>礼物</p>
        </marquee><br>
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            var ws = new WebSocket("ws://__DOMAIN__:__WS_PORT__");
            ws.onopen = function () {
                ws.send('{"cmd": "cmds", "data": ["LIVE_ALL_GIFTS"]}');
            };
            ws.onmessage = function (e) {
                console.log(e.data);
                var json = JSON.parse(e.data);
                var cmd = json['cmd'];
                switch (cmd) {
                    case 'LIVE_ALL_GIFTS':
                        var data = json['data'];
                        var guards = data['guards'];
                        var gifts = data['gifts']; // 是一个数组
                        var allHtml = "<h1 class='line headLine'>感谢以下用户：</h1><hr class='line' style='width:60%'/>";
                        if (guards.length)
                            allHtml += getUserGuards(guards) + "<hr class='line'/>";
                        if (gifts.length)
                            allHtml += mergeUserGifts(gifts);
                        $("#list").html(allHtml);
                        break;
                }
            };
        });

        /**
         * 舰长上船记录（按时间顺序）
         */
        function getUserGuards(histories) {
            var htmls = '';
            for (var i = 0; i < histories.length; i++) {
                // 解析JSON数据
                var danmaku = histories[i];
                console.log(danmaku);
                var nickname = danmaku['nickname'];
                var giftName = danmaku['gift_name'];
                var number = danmaku['number'];
                var guardLevel = danmaku['guard_level'];
                // 送礼动作对象放入map中
                if (number > 1)
                    giftName = giftName + "×" + number;
                var text = nickname + '：' + giftName;
                var color = '';
                if (guardLevel == 1) // 总督
                    color = '#f7b500';
                else if (guardLevel == 2)
                    color = '#e17aff';
                else
                    color = '#00d1f1';
                htmls += "<p class='line'><font color=" + color + ">" + text + '</font></p>';
            }
            return htmls;
        }

        /**
         * 合并每位用户的送礼
         */
        function mergeUserGifts(histories) {
            let userMap = new Map();
            for (var i = 0; i < histories.length; i++) {
                // 解析JSON数据
                var danmaku = histories[i];
                var gift = {
                    nickname: danmaku['nickname'],
                    uid: danmaku['uid'],
                    gift_id: danmaku['gift_id'],
                    gift_name: danmaku['gift_name'],
                    number: danmaku['number'],
                    total_coin: danmaku['total_coin']
                };

                // 送礼动作对象放入map中
                var uid = gift.uid;
                if (!userMap.has(uid)) {
                    var user = {
                        uid: gift.uid,
                        nickname: gift.nickname,
                        total_coin: gift.total_coin,
                        gifts: [gift]
                    };
                    userMap.set(uid, user);
                } else {
                    userGifts = userMap.get(uid);
                    userGifts.total_coin += gift.total_coin;
                    userGifts.gifts.push(gift);
                    userMap.set(uid, userGifts);
                }
            }

            return sortUserGifts(userMap);
        }

        /**
         * 按用户之间、用户自己的礼物价值分别排序
         */
        function sortUserGifts(userMap) {
            var userArray = [];
            for (let user of userMap.values()) {
                // 排序用户的送礼记录
                if (user.gifts.length > 1) {
                    user.gifts.sort(function (a, b) {
                        if (a.total_coin == b.total_coin)
                            return a.number - b.number;
                        return b.total_coin - a.total_coin;
                    });
                }

                userArray.push(user);
            }

            // 排序本次直播用户的送礼总金额
            userArray.sort(function (a, b) {
                if (a.total_coin == b.total_coin)
                    return a.gifts.length - b.gifts.length;
                return b.total_coin - a.total_coin;
            });

            return userGiftsToHtml(userArray);
        }

        function userGiftsToHtml(userArray) {
            var htmls = [];
            userArray.forEach(user => {
                var names = [];
                user.gifts.forEach(gift => {
                    if (gift.number <= 1)
                        names.push(gift.gift_name);
                    else
                        names.push(gift.gift_name + '×' + gift.number);
                });
                htmls.push("<p class='line'>" + user.nickname + '：' + names.join('、') + '</p>');
            });

            var html = htmls.join("\n");
            return html;
        }
    </script>
</body>